package com.example.calendertodo.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.example.calendertodo.EditActivity;
import com.example.calendertodo.R;
import com.example.calendertodo.util.TodoDbOpenHelper;
import com.example.calendertodo.beam.Todo;
import com.example.calendertodo.util.ToastUtil;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{

    private LayoutInflater mLayoutInflater;
    private Context mContext;
    private List<Todo> mBeanList;
    private TodoDbOpenHelper mTodoDbOpenHelper;


    public MyAdapter(Context context, List<Todo> mBeanList){
        this.mBeanList = mBeanList;
        this.mContext = context;
        mLayoutInflater = LayoutInflater.from(mContext);
        mTodoDbOpenHelper = new TodoDbOpenHelper(mContext);
    }


    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {//绑定数据的layout
        View view = mLayoutInflater.inflate(R.layout.list_item_layout, parent, false);
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Todo todo = mBeanList.get(holder.getAdapterPosition());
        String[] dates = todo.getStartTime().split("\t");
        Log.d("tag","----------------------------" + dates);
        String time = dates[1];
        String date = dates[0];
        holder.mTvTitle.setText(todo.getTitle());
        holder.mTvContent.setText(todo.getContent());
        holder.mTvTime.setText(time);
        holder.mTvDate.setText(date);
        holder.ivPicture.setImageBitmap(transferBitmap(todo.getPhoto()));


        int delay = compareTime(getCurrentTimeFormat(),todo.getEndTime());
        if (delay >= 0 && todo.getState().equals("0")) { //说明逾期
            todo.setState("2");
            mTodoDbOpenHelper.updateData(todo);
        }

        //Todo完成和延期的操作
        if (todo.getState().equals("1")) {
            holder.cbComplete.setChecked(true);
            holder.cbComplete.setEnabled(false);
            holder.btnDelete.setVisibility(View.INVISIBLE);
        }else if(todo.getState().equals("2")) {
            holder.rlContainer.setBackgroundColor(ContextCompat.getColor(mContext,R.color.red));
            holder.cbComplete.setVisibility(View.INVISIBLE);
            holder.btnDelete.setVisibility(View.INVISIBLE);
        }

        //每一项中的删除按钮控件
        holder.btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                //数据库中删除
//                int row = mTodoDbOpenHelper.deleteFromDbById(todo.getId());
                //如果row大于0说明删除成功，再从列表中删除
                    removeData(holder.getAdapterPosition());
                    todo.setState("3");
                    mTodoDbOpenHelper.updateData(todo);
                    ToastUtil.toastShort(mContext,"你取消了Todo");
            }
        });

        //checkbox控件事件
        holder.cbComplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(holder.cbComplete.isChecked()) {
                    todo.setState("1");
                    mTodoDbOpenHelper.updateData(todo);
                    holder.btnDelete.setVisibility(View.INVISIBLE);
                    holder.cbComplete.setEnabled(false);
                    ToastUtil.toastShort(mContext,"Todo完成！");
                }
            }
        });


        //每一项的点击事件
        holder.rlContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (todo.getPhoto().equals("null") && TextUtils.isEmpty(todo.getContent())) {
                    ToastUtil.toastShort(mContext,"Todo暂无详细信息，长按添加");
                    return;
                }else {
                    if (holder.ivPicture.getVisibility() == View.GONE ){
                        holder.ivPicture.setVisibility(View.VISIBLE);
                        holder.mTvContent.setVisibility(View.VISIBLE);
                        holder.ivArrow.setImageResource(R.drawable.ic_baseline_arrow_drop_up_24);
                    }else {
                        holder.ivPicture.setVisibility(View.GONE);
                        holder.mTvContent.setVisibility(View.GONE);
                        holder.ivArrow.setImageResource(R.drawable.ic_baseline_arrow_drop_down_24);
                    }
                }


            }
        });

        //长点击事件,点击进入编辑
        holder.rlContainer.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if(todo.getState().equals("0")) {
                    Intent intent = new Intent(mContext, EditActivity.class);
                    intent.putExtra("todo",todo);
                    mContext.startActivity(intent);
                }else if(todo.getState().equals("1")){
                    ToastUtil.toastShort(mContext,"Todo已完成");
                }else if(todo.getState().equals("2")){
                    ToastUtil.toastShort(mContext,"Todo逾期");
                }

                return true;
            }
        });

    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    //todo的结束时间与当前时间对比
    private int compareTime(String current_date,String end_date) {
        Log.d("tag","---------当前日期----------" + current_date + "\t截止日期" + end_date);
        return current_date.compareTo(end_date);
    }

    //字符串转为bitmap
    public Bitmap transferBitmap(String photo) {
        Uri imageUri;
        InputStream inputStream = null;
        try {
            imageUri= Uri.parse(String.valueOf(photo));
            inputStream = mContext.getContentResolver().openInputStream(imageUri);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        return bitmap;
    }


    @Override
    public int getItemCount() {
        return mBeanList.size();
    }


    //将数据列表刷新
    public void refreshData(List<Todo> todo) {
        this.mBeanList = todo;
        notifyDataSetChanged();
    }

    //按位置删除，此处只是删除了recycleView中的数据还需要在数据库中删除
    public void removeData(int pos) {
        mBeanList.remove(pos);
        notifyItemRemoved(pos);

    }

    private String getCurrentTimeFormat() { //获取当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd\tHH:mm");
        Date date = new Date();
        return simpleDateFormat.format(date);
    }


    //列表视图的适配器
    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView mTvTitle;
        TextView mTvContent;
        TextView mTvTime;
        TextView mTvDate;
        CheckBox cbComplete;
        Button btnDelete;
        ImageView ivPicture,ivArrow;

        ViewGroup rlContainer;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            this.mTvTitle = itemView.findViewById(R.id.tv_title);
            this.mTvContent = itemView.findViewById(R.id.tv_content);
            this.mTvTime = itemView.findViewById(R.id.tv_time);
            this.mTvDate = itemView.findViewById(R.id.tv_date);
            this.cbComplete= itemView.findViewById(R.id.cb_complete);
            this.btnDelete= itemView.findViewById(R.id.btn_delete);
            this.rlContainer = itemView.findViewById(R.id.rl_item_container);
            this.ivPicture = itemView.findViewById(R.id.iv_picture);
            this.ivArrow = itemView.findViewById(R.id.iv_arrow);
        }
    }
}
